package cn.action.news;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;

import cn.action.BaseAction;
import cn.beans.NewsCategory;
import cn.busiBean.NewsCategoryBean;

@SuppressWarnings("unchecked")
public class NewsCategoryAction extends BaseAction {

	private NewsCategory nc;
	private List listNc;
	private String ncId;
	private String parentNcId;
	private String errorinfo;
	
	/**
	 * 添加新闻类目
	 * @throws Exception
	 */
	public void addNewsCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				
				if(null != parentNcId && !"".equals(parentNcId.trim())){
					
					Object[] levelAndTurnnum = this.getLevelAndTurnnum(parentNcId);
					if(0 == (Integer)levelAndTurnnum[0] && 0 == (Integer)levelAndTurnnum[1] && null == levelAndTurnnum[2]){
						this.sendMsgAjax("parentNc", null);
					}else{
						NewsCategory newNc = new NewsCategory();
						newNc.setNameCn(nc.getNameCn());
						newNc.setNameEn(nc.getNameEn());
						newNc.setParentId(parentNcId);
						newNc.setLevels((Integer)levelAndTurnnum[0]);
						newNc.setTurnnumber((Integer)levelAndTurnnum[1]);
						newNc.setPath((String)levelAndTurnnum[2] + "/" + parentNcId);
						
						commonservice.saveDemo(newNc);
						
						this.sendMsgAjax("success", null);
					}
					
				}else{
					this.sendMsgAjax("parentId", null);
				}
				
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 查询新闻类目详情
	 * @return
	 */
	public String newsCategoryDetail(){
		if(null != ncId){
			nc = commonservice.findById(ncId, new NewsCategory());
		}
		return SUCCESS;
	}
	
	/**
	 * 修改新闻类目
	 * @throws Exception
	 */
	public void updateNewsCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				NewsCategory category = commonservice.findById(ncId, new NewsCategory());
				category.setNameCn(nc.getNameCn());
				category.setNameEn(nc.getNameEn());
				
				commonservice.updateDemo(category);
				this.sendMsgAjax("success", null);
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 删除新闻类目
	 * @throws Exception
	 */
	public void deleteNewsCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				String[] ids = ncId.split(",");
				int length = ids.length;
				for(int i=0;i<length;i++){
					NewsCategory category = commonservice.findById(ids[i], new NewsCategory());
					if(null != category){
						List list = this.getCategoryList(category.getId(), null);
						if(null != list)
							commonservice.deleteAll(list);
						String hql = "FROM News n WHERE n.category.id = ? OR n.category.path like '%" + category.getId() + "%'";
						Object[] param = { category.getId() };
						List listNews = findSomeByHQL.findDataByHql(hql, param);
						if(null != listNews)
							commonservice.deleteAll(listNews);
						
						commonservice.deleteDemo(category, null);
					}
				}
				
				this.sendMsgAjax("success", null);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 查询类目列表
	 * @return
	 */
	public String listCategory(){
		listNc = this.getCategoryList("root", null);
		return SUCCESS;
	}
	
	/**
	 * AJAX查询类目列表
	 * @return
	 */
	public void loadCategory() throws Exception{
		listNc = this.getCategoryList("root", null);
		if(null != listNc){
			List list = new ArrayList();
			int size = listNc.size();
			for(int i=0;i<size;i++){
				NewsCategory nsc = (NewsCategory)listNc.get(i);
				NewsCategoryBean ncb = new NewsCategoryBean();
				ncb.setId(nsc.getId());
				ncb.setNameCn(nsc.getNameCn());
				ncb.setNameEn(nsc.getNameEn());
				ncb.setLevels(nsc.getLevels());
				ncb.setTurnnumber(nsc.getTurnnumber());
				list.add(ncb);
			}
			String jsonResult = this.changeListToStr(list);
			this.sendMsgAjax(jsonResult, null);
		}
		
	}
	
	/**
	 * 调整类目顺序,选中的类目向上移动一位
	 * @throws Exception
	 */
	public void newsCategoryUp() throws Exception{
		try{
			
			NewsCategory category = commonservice.findById(ncId, new NewsCategory());
			this.changePosition(category.getParentId(), category.getTurnnumber(), "up");
			
			this.sendMsgAjax("success", null);
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 调整类目顺序,选中的类目向下移动一位
	 * @throws Exception
	 */
	public void newsCategoryDown() throws Exception{
		try{
			
			NewsCategory category = commonservice.findById(ncId, new NewsCategory());
			this.changePosition(category.getParentId(), category.getTurnnumber(), "down");
			
			this.sendMsgAjax("success", null);
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}

	public NewsCategory getNc() {
		return nc;
	}

	public void setNc(NewsCategory nc) {
		this.nc = nc;
	}

	public List getListNc() {
		return listNc;
	}

	public void setListNc(List listNc) {
		this.listNc = listNc;
	}

	public String getNcId() {
		return ncId;
	}

	public void setNcId(String ncId) {
		this.ncId = ncId;
	}

	public String getParentNcId() {
		return parentNcId;
	}

	public void setParentNcId(String parentNcId) {
		this.parentNcId = parentNcId;
	}
	
	public String getErrorinfo() {
		return errorinfo;
	}

	public void setErrorinfo(String errorinfo) {
		this.errorinfo = errorinfo;
	}

	/**
	 * 获取新孩子的等级与排序号
	 * @param parentNcId
	 * @return
	 */
	private Object[] getLevelAndTurnnum(String parentNcId){
		
		NewsCategory nc = commonservice.findById(parentNcId, new NewsCategory());
		
		if(null != nc){
			int newLevels = nc.getLevels() + 1;
			
			String hql = "SELECT MAX(nc.turnnumber) FROM NewsCategory AS nc WHERE nc.parentId = ?";
			Object[] param = { parentNcId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int turnnum = 0;
			if(null != list && list.size() != 0){
				if(null != list.get(0))
					turnnum = (Integer)list.get(0);
			}
			turnnum = turnnum + 1;
			Object[] result = { newLevels, turnnum, nc.getPath() };
			
			return result;
		}else if("root".equals(parentNcId)){
			int newLevels = 1;
			
			String hql = "SELECT MAX(nc.turnnumber) FROM NewsCategory AS nc WHERE nc.parentId = ?";
			Object[] param = { parentNcId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int turnnum = 0;
			if(null != list && list.size() != 0){
				if(null != list.get(0))
					turnnum = (Integer)list.get(0);
			}
			turnnum = turnnum + 1;
			Object[] result = { newLevels, turnnum, "/root" };
			
			return result;
		}else{
			Object[] result = { 0, 0, null };
			
			return result;
		}
		
	}
	
	/**
	 * 通过递归获取类目列表
	 * @param parentId 父类目的ID
	 * @param resultList 保存结果的List
	 * @return 
	 */
	private List getCategoryList(String parentId, List resultList){
		if(null == parentId){
			parentId = "root";
		}
		if(null == resultList){
			resultList = new ArrayList();
		}
		
		String hql = "FROM NewsCategory AS nc WHERE nc.parentId = ? ORDER BY nc.turnnumber";
		Object[] param = { parentId };
		List list = findSomeByHQL.findDataByHql(hql, param);
		if(null != list && 0 != list.size()){
			int size = list.size();
			for(int i=0; i<size; i++){
				NewsCategory category = (NewsCategory)list.get(i);
				resultList.add(category);
				resultList = getCategoryList(category.getId(), resultList);
			}
		}
		
		return resultList;
		
	}
	
	/**
	 * 类目顺序升降
	 * @param parentId 当前类目的父类目ID
	 * @param turnnumber 当前类目的排序号
	 * @param type 升降类型(up 或 down)
	 */
	private void changePosition(String parentId, Integer turnnumber, String type){
		try{
			String hql = "FROM NewsCategory AS nc WHERE nc.parentId = ?";
			Object[] param = { parentId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int size = list.size();
			type = type.toLowerCase();
			if("up".equals(type)){
				if(turnnumber > 1){
					int num = 0;
					if(size >= 2){
						for(int i=0; i<size; i++){
							NewsCategory category = (NewsCategory)list.get(i);
							if(turnnumber == category.getTurnnumber()){
								category.setTurnnumber(turnnumber - 1);
								num ++;
							}else if(turnnumber - 1 == category.getTurnnumber()){
								category.setTurnnumber(turnnumber);
								num ++;
							}
							commonservice.updateDemo(category);
							if(2 == num){
								break;
							}
						}
					}
				}
			}else if("down".equals(type)){
				if(turnnumber < size){
					int num = 0;
					if(size >= 2){
						for(int i=0; i<size; i++){
							NewsCategory category = (NewsCategory)list.get(i);
							if(turnnumber == category.getTurnnumber()){
								category.setTurnnumber(turnnumber + 1);
								num ++;
							}else if(turnnumber + 1 == category.getTurnnumber()){
								category.setTurnnumber(turnnumber);
								num ++;
							}
							commonservice.updateDemo(category);
							if(2 == num){
								break;
							}
						}
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
